//
//  RHBatteryCellFormVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/27.
//

#import "RHBatteryCellFormVC.h"
#import "RHBatteryClusterFormCell.h"
#import "RHDevPackModel.h"

@interface RHBatteryCellFormVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)UIView *headerView;
@property (nonatomic, strong) NSArray *headerDataArr;

@property (nonatomic, strong) NSArray *packDataArr;

@property (nonatomic ,strong) UITableView *tableView;
@end

@implementation RHBatteryCellFormVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self getMasterData];
    [self getPackInfoWithMaster:self.masterSN];
    [self setupUI];
}


-(void)setupUI
{
   
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = self.headerView;
    [_tableView registerClass:[RHBatteryClusterFormCell class] forCellReuseIdentifier:@"RHBatteryClusterFormCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getMasterData];
        [weakSelf getPackInfoWithMaster:weakSelf.masterSN];
    }];
}
#pragma mark ------- network -----
-(void)getMasterData
{
    [QMUITips showLoadingInView:self.view];
    NSArray *masterParas = @[@"Mtr_TV",
                             @"Mtr_Cur",
                             @"Mtr_SOC",
                             @"Mtr_SOH"
    ];
    
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"endpointTypeCode":@"Master",
                           @"keyCodes":masterParas,
                           @"endpointSn":self.masterSN
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                [self updateMasterData:request.responseObject[@"data"]];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

//根据master获取 pack和电芯数据
-(void)getPackInfoWithMaster:(NSString*)masterSN
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"masterSn":masterSN};
    [RHDevPackModel startGetWithCompletionAPIKey:H_getPackCellData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
          
            self.packDataArr = resultModel.data;
          
            [self.packDataArr enumerateObjectsUsingBlock:^(RHDevPackModel  *_Nonnull packModel, NSUInteger idx, BOOL * _Nonnull stop) {
                NSMutableArray *cellArr = [NSMutableArray array];
                [packModel.volt enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    RHDevCellModel *cellModel = [[RHDevCellModel alloc]init];
                    cellModel.volt = [NSString stringWithFormat:@"%.1f",[ValidNullData(obj) floatValue]];
                    if(idx<packModel.temp.count){
                        cellModel.temp = [NSString stringWithFormat:@"%.1f",[ValidNullData(packModel.temp[idx]) floatValue]];
                    }
                    [cellArr addObject:cellModel];
                }];
                packModel.cells = cellArr.copy;
            }];
            [self.tableView reloadData];

        }
        [self.tableView endHeaderRefresh];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
        
}

-(void)updateMasterData:(NSDictionary*)dic
{
    kWeakSelf;
    NSArray *dataKeys = @[@"Mtr_SOC",@"Mtr_SOH",@"Mtr_TV",@"Mtr_Cur"];
    [self.headerDataArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *lab = [weakSelf.headerView viewWithTag:100+idx];
        NSString *key = dataKeys[idx];
        lab.text = [NSString stringWithFormat:@"%@%@",ValidNullDataToString(dic[key], @"--"),dic[CellUint]];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.packDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHDevPackModel *packModel = self.packDataArr[section];
    
    return packModel.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 65;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 65)];
    contentView.backgroundColor = CFTabViewBgColor;
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 50)];
    headView.layer.cornerRadius = 8;
    headView.layer.masksToBounds = YES;
    headView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    headView.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:headView];
    
    UIImageView *leftIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"battery_form_down"]];
    [headView addSubview:leftIcon];
    
    UIImageView *rightIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"battery_form_icon"]];
    [headView addSubview:rightIcon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(18);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = [NSString stringWithFormat:@"PACK %ld#",section+1];
    [headView addSubview:titleLab];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [headView addSubview:line];
    
    [leftIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [rightIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftIcon.mas_right).offset(15);
        make.centerY.equalTo(leftIcon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
   return contentView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    contentView.backgroundColor = CFTabViewBgColor;
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 8)];
    footView.layer.cornerRadius = 8;
    footView.layer.masksToBounds = YES;
    footView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    footView.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:footView];
    return contentView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    RHBatteryClusterFormCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHBatteryClusterFormCell"];
    cell.packNoLab.text = [NSString stringWithFormat:@"%@: %ld",@"电芯编号".rh_localized,indexPath.row+1];
    RHDevPackModel *packModel = self.packDataArr[indexPath.section];
    cell.cellModel = packModel.cells[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}


-(UIView *)headerView
{
    if(!_headerView){
        self.headerDataArr = @[@{CellTitle:@"SOC",CellIcon:@"dev_cell_soc",CellUint:@"(%)"},
                                @{CellTitle:@"SOH",CellIcon:@"dev_cell_soh",CellUint:@""},
                                @{CellTitle:@"电压".rh_localized,CellIcon:@"dev_cell_vol",CellUint:@"(V)"},
                                @{CellTitle:@"电流".rh_localized,CellIcon:@"dev_cell_ele",CellUint:@"(A)"}
                                ];
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 64*2+35)];
        _headerView.backgroundColor = CFTabViewBgColor;
        
        __block UIView *lastView;
        __block CGFloat itemWidth = (kUI_WINDOW_W - 45)/2;
        [self.headerDataArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
            UIView *itemView = [self itemViewWithTitle:dic[CellTitle] icon:dic[CellIcon] index:idx];
            [_headerView addSubview:itemView];
            if(idx == 0){
                [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.top.mas_offset(15);
                    make.width.offset(itemWidth);
                    make.height.offset(64);
                }];
            }else{
                if(idx%2==0){
                    [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.mas_offset(15);
                        make.size.equalTo(lastView);
                        make.top.equalTo(lastView.mas_bottom).offset(15);
                    }];
                }else{
                    [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(lastView.mas_right).offset(15);
                        make.size.top.equalTo(lastView);
                    }];
                }
            }
            lastView = itemView;
        }];
    }
    return _headerView;
}

-(UIView*)itemViewWithTitle:(NSString*)title icon:(NSString*)icon index:(NSInteger)index;
{
    UIView *bgView = kView;
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:icon]];
    [bgView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(25));
        make.left.top.mas_offset(15);
    }];
    
   QMUILabel* contentLab = [[QMUILabel alloc]init];
    contentLab.text = @"--";
    contentLab.font = [UIFont boldSystemFontOfSize:16];
    contentLab.textAlignment = NSTextAlignmentLeft;
    contentLab.textColor = kCOLOR_HEX(@"3F4443");
    contentLab.tag = 100 + index;
    [bgView addSubview:contentLab];
    
    QMUILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.text = title;
    titleLab.font = [UIFont systemFontOfSize:13];
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.textColor = kCOLOR_HEX(@"3F4443");
    [bgView addSubview:titleLab];
    
    kWeakSelf;
    [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(kScaleW(15));
        make.top.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentLab);
        make.top.equalTo(contentLab.mas_bottom).offset(5);
        make.right.mas_offset(-15);
    }];
    
    return bgView;
}




#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

@end
